package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.auth.entity.ApplicationInfo;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties props;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ApplicationInfoMapper appMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public void login(String username, String password, HttpServletResponse response) {

        UserDTO userDTO = userClient.queryUserByUsernameAndPassword(username, password);

        if(null==userDTO){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        UserInfo userInfo = BeanHelper.copyProperties(userDTO, UserInfo.class);

        //用户的角色，目前没有设置，给个随机值。
        userInfo.setRole("admin");

        //写配置文件，配置公钥私钥等地址，以及过期等基本信息，在业务中套用
        String token= JwtUtils.generateTokenExpireInMinutes(userInfo,props.getPrivateKey(),props.getUser().getExpire());

        CookieUtils.newBuilder()
                .response(response)
                .httpOnly(true)
                .domain(props.getUser().getCookieDomain())
                .name(props.getUser().getCookieName()).value(token)
                .maxAge(props.getUser().getCookieExpire())
                .build();
    }

    public UserInfo verify(HttpServletRequest request,HttpServletResponse response) {
        try {
            String token = CookieUtils.getCookieValue(request, props.getUser().getCookieName());
            Payload<UserInfo> payLoad = JwtUtils.getInfoFromToken(token, props.getPublicKey(), UserInfo.class);

            Boolean bool = redisTemplate.hasKey(payLoad.getId());
            if(bool==null&&bool){
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }

            //校验成功后重新生成token
            String newToken = JwtUtils.generateTokenExpireInMinutes(payLoad.getInfo(), props.getPrivateKey(), props.getUser().getExpire());
            CookieUtils.newBuilder()
                    .response(response)
                    .httpOnly(true)
                    .domain(props.getUser().getCookieDomain())
                    .name(props.getUser().getCookieName()).value(newToken)
                    .maxAge(props.getUser().getCookieExpire())
                    .build();

            return payLoad.getInfo();
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        String token = CookieUtils.getCookieValue(request, props.getUser().getCookieName());
        Payload<Object> playload = JwtUtils.getInfoFromToken(token, props.getPublicKey());
        String id = playload.getId();
        long time = playload.getExpiration().getTime() - System.currentTimeMillis();
        if(time>5){
            redisTemplate.opsForValue().set(id,"",time, TimeUnit.MILLISECONDS);
        }
        CookieUtils.deleteCookie(props.getUser().getCookieName(),props.getUser().getCookieDomain(),response);
    }

    public String authenticate(Long id, String secret) {
        ApplicationInfo app = appMapper.selectByPrimaryKey(id);
        if(app==null){
            throw new LyException(ExceptionEnum.INVALID_SERVER_ID_SECRET);
        }
        if(!passwordEncoder .matches(secret,app.getSecret())){
            throw new LyException(ExceptionEnum.INVALID_SERVER_ID_SECRET);
        }
        AppInfo appInfo = new AppInfo();
        appInfo.setId(id);
        appInfo.setServiceName(app.getServiceName());
        appInfo.setTargetList(appMapper.queryTargetIdList(id));
        String token = JwtUtils.generateTokenExpireInMinutes(appInfo, props.getPrivateKey(), props.getApp().getExpire());
        return token;
    }
}
